package com.yinNuo.collectWool.core;

import com.yinNuo.collectWool.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author: yinNuo
 * create at: 2021/12/6 下午7:53
 * @description: 接口返回处理类
 */
@Slf4j
public class BaseAPI {

    //api的基础路径，用于拼接文件路径
    protected static String API_BASE_PATH = "";

    /**
     * 每次请求前执行
     * @param request
     */
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request) {
        API_BASE_PATH = HttpUtils.getContextHttpUri(request);
    }

    /**
     * 请求异常时执行
     * @param e
     * @return
     */
    @ExceptionHandler
    public Object exception(Exception e) {
        log.error(getTrace(e));
        return Response.failed("数据异常");
    }

    public static String getTrace(Throwable e) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        e.printStackTrace(writer);
        StringBuffer buffer = stringWriter.getBuffer();
        return "[" + e.getMessage() + "]" + buffer.toString();
    }
}
